package com.test30_IO流;

import org.junit.Test;

import java.io.*;

/**
 * 对象序列化
 */
public class Demo16_Serializable {

    /**
     * 实现对象序列化
     */
    @Test
    public void test1() throws Exception {
        File file = new File("F:" + File.separator + "muyan" + File.separator + "book.ser");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        Book book = new Book("Java从入门到项目实战", "李兴华", 99.8);
        oos.writeObject(book);  // 序列化输出
        oos.close();
    }

    /**
     * 对象反序列化
     */
    @Test
    public void test2() throws Exception {
        File file = new File("F:" + File.separator + "muyan" + File.separator + "book.ser");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        Book book = (Book) ois.readObject();
        System.out.println(book);
        ois.close();
    }
}

class Book implements Serializable {    // 本类对象可以序列化处理
    private String title;
    /** 某些属性不希望被序列化，可以使用transient关键字 */
    private transient String author;    // 此时该属性不会被保存
    private double price;

    public Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    @Override
    public String toString() {
        return "【图书】名称：" + this.title + "、作者：" + this.author + "、价格：" + this.price;
    }
}
